﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Telerik.Web.Mvc;

namespace Presentation.Web.Admin.Controllers
{
    [HandleError]
    public class ClientController : Infrastructure.Crosscutting.NetFramework.Controllers.BaseController
    {

        Application.Admin.MobileClient.IMobileClientService clientService;

        public ClientController(Infrastructure.Crosscutting.NetFramework.IWorkContext work,
            Application.Admin.MobileClient.IMobileClientService client)
            : base(work)
        {
            if (client == null)
            {
                throw new ArgumentNullException("clientService is null");
            }
            clientService = client;
        }

        #region client

        public ActionResult Index()
        {
            var data = this.GetClientTrueState();
            return View(data.ToDto());
        }

        [GridAction]
        public JsonResult AjaxIndex(string searchKey)
        {
            var data = this.GetClientTrueState();
            if (!string.IsNullOrEmpty(searchKey))
            {
                data = data.Where(e => e.DeviceToken.Contains(searchKey));
            }
            var dto = data.ToDto();
            var model = new GridModel<Domain.Dto.MobileClientDto>
            {
                Data = dto,
                Total = dto.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [GridAction]
        [HttpPost]
        public JsonResult Delete(int id)
        {
            var delete = clientService.Get(id);
            if (delete != null)
            {
                clientService.DeleteTrue(delete, this.WorkContext.CurrentUser);
            }
            var data = this.GetClientTrueState().ToDto();
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult MulDelete(FormCollection del)
        {
            var res = false;
            var message = "";
            var selectedList = del.GetValues("selectRow");
            if (selectedList != null && selectedList.Count() > 0)
            {
                res = clientService.DeleteTrue(selectedList.ToIntList(), this.WorkContext.CurrentUser);
                message = res == true ? "" : "删除失败了，T_T";
            }
            //返回空，是为了不再请求数据，因为他自己会重新binding的
            return Json(new { success = res, message = message }, JsonRequestBehavior.AllowGet);
        }

        [GridAction]
        [HttpPost]
        public JsonResult Edit(Domain.Dto.MobileClientDto dto)
        {
            if (dto != null && dto.Id > 0)
            {
                var entity = clientService.Get(dto.Id);
                if (entity != null)
                {
                    entity.Name = string.IsNullOrEmpty(dto.Name) ? "" : dto.Name.Trim();
                    entity.Remark = string.IsNullOrEmpty(dto.Remark) ? "" : dto.Remark.Trim();
                    clientService.Modify(entity, this.WorkContext.CurrentUser);
                }
            }
            var data = this.GetClientTrueState().ToDto();
            var model = new GridModel<Domain.Dto.MobileClientDto>
            {
                Data = data,
                Total = data.Count()
            };
            return new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

        [HttpGet]
        public JsonResult Search(string term)
        {
            if (!string.IsNullOrEmpty(term))
            {
                var data = this.GetClientTrueState().Where(e => e.DeviceToken.Contains(term.Trim()))
                            .OrderBy(e => e.Id).Take(10)
                            .Select(e => e.DeviceToken).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
            else
            {
                var data = this.GetClientTrueState().OrderBy(e => e.Id).Take(10)
                            .Select(e => e.DeviceToken).Distinct();
                return Json(data.ToList(), JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult Chart()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Chart(DateTime? start, DateTime? end)
        {
            end = end.HasValue ? end.Value.AddDays(1) : System.DateTime.Now;
            var now = System.DateTime.Now;
            start = start.HasValue ? start.Value : now.AddDays(-now.Day + 1)
              .AddHours(-now.Hour).AddMinutes(-now.Minute)
              .AddSeconds(-now.Second).AddMilliseconds(-now.Millisecond);

            var data = this.GetClientTrueState((DateTime)start, (DateTime)end);
            var model = (from client in data
                         group client by client.Name into temp
                         select new Application.Admin.Dto.ClientDto()
                         {
                             Name = temp.Key,
                             Total = temp.Count()
                         });

            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ChartReport()
        {
            return View();
        }

        #endregion


        #region util

        protected IQueryable<Domain.Entity.MobileClient> GetClientTrueState()
        {
            var data = clientService.GetList().Where(e => e.State == true)
                .OrderByDescending(e => e.Id).Distinct();
            return data;
        }

        protected IQueryable<Domain.Entity.MobileClient> GetClientTrueState(DateTime start, DateTime end)
        {
            var data = GetClientTrueState().Where(d => d.AddTime >= start && d.AddTime <= end)
                .AsQueryable();
            return data;
        }

        #endregion
    }
}
